import React, { useContext, useState } from 'react';
import {Link} from 'react-router-dom';
import {Form, Input, FormGroup, FormFeedback, Label, Row, Col, Button} from 'reactstrap';

import {AuthContext} from '../auth-context';

const Login = () => {

  const {login} = useContext(AuthContext);

  const [mail, setMail] = useState('');
  const [pass, setPass] = useState('');
  const [fail, setFail] = useState(false);

  const updateMail = (e) => {
    setMail(e.target.value);
  }

  const updatePass = (e) => {
    setPass(e.target.value);
  }

  const submitLogin = async (e) => {
    e.preventDefault();
    const res = await login(mail, pass);
    if (!res.ok) {
      setFail(true);
    }
  }

  return (
    <div style={{}}>
      <Form onSubmit={submitLogin}>
        <FormGroup>
          <Label for="mail" sm={2}>Email</Label>
          <Input id="mail" type="email" placeholder="Email address" value={mail} onInput={updateMail}/>
        </FormGroup>
        <Row>
        <FormGroup>
          <Label for="pass" sm={2}>Password</Label>
          <Input id="pass" type="password" placeholder="Password" value={pass} onInput={updatePass} invalid={fail}/>
          <FormFeedback>Login unsuccessful. Try again or register new user.</FormFeedback>
        </FormGroup>
        </Row>
        <Row>
          <Col xs='6'>
            <FormGroup>
              <Label for='login' sm={2}  style={{width: '100%'}}>Login</Label>
              <Button id='login' type="submit">Login</Button>
            </FormGroup>
          </Col>
          <Col xs='6'>
            <FormGroup>
              <Label for='reg' sm={2}  style={{width: '100%'}}>Not registered?</Label>
              <Link to='/reg'>
                <Button type='button'>
                  <span>Go to Register</span>
                </Button>
              </Link>
            </FormGroup>
          </Col>
        </Row>
      </Form>
    </div>
  );
};

export default Login;